import { apiClient } from './apiClient';
import type { 
  Department, 
  PaginatedResponse, 
  CreateDepartmentRequest,
  UpdateDepartmentRequest 
} from '@/types';

export interface GetDepartmentsParams {
  page?: number;
  pageSize?: number;
  search?: string;
  status?: 'active' | 'inactive';
  parentId?: string;
  tenantId?: string;
  organizationId?: string;
}

export interface DepartmentBatchOperationParams {
  ids: string[];
  operation: 'delete' | 'activate' | 'deactivate' | 'move';
  targetParentId?: string;
}

export interface DepartmentTreeNode extends Department {
  children?: DepartmentTreeNode[];
  level?: number;
  userCount?: number;
}

class DepartmentService {
  private baseUrl = '/api/departments';

  /**
   * 获取部门列表
   */
  async getDepartments(params: GetDepartmentsParams): Promise<Department[]> {
    const { data } = await apiClient.get<PaginatedResponse<Department>>(this.baseUrl, {
      params
    });
    return data.items;
  }

  /**
   * 获取部门详情
   */
  async getDepartmentById(id: string): Promise<Department> {
    const { data } = await apiClient.get<Department>(`${this.baseUrl}/${id}`);
    return data;
  }

  /**
   * 创建部门
   */
  async createDepartment(department: CreateDepartmentRequest): Promise<Department> {
    const { data } = await apiClient.post<Department>(this.baseUrl, department);
    return data;
  }

  /**
   * 更新部门
   */
  async updateDepartment(id: string, department: UpdateDepartmentRequest): Promise<Department> {
    const { data } = await apiClient.put<Department>(`${this.baseUrl}/${id}`, department);
    return data;
  }

  /**
   * 删除部门
   */
  async deleteDepartment(id: string): Promise<void> {
    await apiClient.delete(`${this.baseUrl}/${id}`);
  }

  /**
   * 批量删除部门
   */
  async deleteDepartments(ids: string[]): Promise<void> {
    await apiClient.delete(`${this.baseUrl}/batch`, {
      data: { ids }
    });
  }

  /**
   * 批量操作部门
   */
  async batchOperation(params: DepartmentBatchOperationParams): Promise<void> {
    await apiClient.post(`${this.baseUrl}/batch-operation`, params);
  }

  /**
   * 获取部门树结构
   */
  async getDepartmentTree(params?: {
    tenantId?: string;
    organizationId?: string;
    includeUserCount?: boolean;
  }): Promise<DepartmentTreeNode[]> {
    const { data } = await apiClient.get<DepartmentTreeNode[]>(`${this.baseUrl}/tree`, {
      params
    });
    return data;
  }

  /**
   * 移动部门到新的父级部门
   */
  async moveDepartment(id: string, newParentId: string | null): Promise<Department> {
    const { data } = await apiClient.put<Department>(`${this.baseUrl}/${id}/move`, {
      parentId: newParentId
    });
    return data;
  }

  /**
   * 获取部门成员列表
   */
  async getDepartmentMembers(id: string, params?: {
    page?: number;
    pageSize?: number;
    search?: string;
  }): Promise<any[]> {
    const { data } = await apiClient.get<PaginatedResponse<any>>(`${this.baseUrl}/${id}/members`, {
      params
    });
    return data.items;
  }

  /**
   * 添加部门成员
   */
  async addDepartmentMembers(id: string, userIds: string[]): Promise<void> {
    await apiClient.post(`${this.baseUrl}/${id}/members`, { userIds });
  }

  /**
   * 移除部门成员
   */
  async removeDepartmentMembers(id: string, userIds: string[]): Promise<void> {
    await apiClient.delete(`${this.baseUrl}/${id}/members`, {
      data: { userIds }
    });
  }

  /**
   * 设置部门负责人
   */
  async setDepartmentManager(id: string, managerId: string): Promise<Department> {
    const { data } = await apiClient.put<Department>(`${this.baseUrl}/${id}/manager`, {
      managerId
    });
    return data;
  }

  /**
   * 取消部门负责人
   */
  async removeDepartmentManager(id: string): Promise<Department> {
    const { data } = await apiClient.delete<Department>(`${this.baseUrl}/${id}/manager`);
    return data;
  }

  /**
   * 获取部门统计信息
   */
  async getDepartmentStats(id: string): Promise<{
    userCount: number;
    subDepartmentCount: number;
    activeUserCount: number;
    inactiveUserCount: number;
  }> {
    const { data } = await apiClient.get<{
      userCount: number;
      subDepartmentCount: number;
      activeUserCount: number;
      inactiveUserCount: number;
    }>(`${this.baseUrl}/${id}/stats`);
    return data;
  }

  /**
   * 验证部门代码是否可用
   */
  async validateDepartmentCode(code: string, excludeId?: string): Promise<boolean> {
    const { data } = await apiClient.get<{ available: boolean }>(`${this.baseUrl}/validate-code`, {
      params: { code, excludeId }
    });
    return data.available;
  }

  /**
   * 导出部门结构
   */
  async exportDepartments(format: 'json' | 'csv' | 'excel' = 'json'): Promise<Blob> {
    const response = await apiClient.get(`${this.baseUrl}/export`, {
      params: { format },
      responseType: 'blob'
    });
    return response.data;
  }

  /**
   * 导入部门结构
   */
  async importDepartments(file: File): Promise<{
    success: number;
    failed: number;
    errors: string[];
  }> {
    const formData = new FormData();
    formData.append('file', file);
    
    const { data } = await apiClient.post<{
      success: number;
      failed: number;
      errors: string[];
    }>(`${this.baseUrl}/import`, formData, {
      headers: {
        'Content-Type': 'multipart/form-data'
      }
    });
    return data;
  }

  /**
   * 获取部门路径（从根部门到当前部门的完整路径）
   */
  async getDepartmentPath(id: string): Promise<Department[]> {
    const { data } = await apiClient.get<Department[]>(`${this.baseUrl}/${id}/path`);
    return data;
  }

  /**
   * 搜索部门
   */
  async searchDepartments(query: string, params?: {
    tenantId?: string;
    organizationId?: string;
    limit?: number;
  }): Promise<Department[]> {
    const { data } = await apiClient.get<Department[]>(`${this.baseUrl}/search`, {
      params: {
        q: query,
        ...params
      }
    });
    return data;
  }
}

export const departmentService = new DepartmentService();